cd "/Users/nicolegorton/Dropbox/World Bank/OTN_LAC/proj_code/data/gridmaps"

global countries "/Users/nicolegorton/Dropbox/World Bank/OTN_LAC/proj_code/data/COUNTRY_SHP/countries_shp/"

local countries Argentina Mexico Ecuador Brazil Peru Colombia

foreach c in `countries' {
	cap shp2dta using `c', database(`c'_db) coordinates(`c'_coords) genid(id)
	cap shp2dta using `c'_roads, database(`c'_roads_db) coordinates(`c'_roads_coords) genid(id)
	
	use `c'_roads_coords, clear
	gen id = _ID
	merge m:1 id using `c'_roads_db, nogen
	keep if dI > 0.001 & dI<.
	
	gen percentile = .
	sum dI , det
	replace percentile = 0 if dI<r(p50)
	replace percentile = 50 if dI>=r(p50) &  dI<r(p75)
	replace percentile = 75 if dI>=r(p75) &  dI<r(p90)
	replace percentile = 90 if dI>=r(p90) 
			
	save `c'_roads_coords_wI,replace
	
	use `c'_db, clear

	sum chat if chat<1, det
	local minlow=r(min)
	local p25low =r(p25) 
	local p75low =r(p75) 
	local maxlow=r(max)

	sum chat if chat>1, det
	local minhi=r(min)
	local p25hi =r(p25) 
	local p75hi =r(p75) 
	local maxhi= r(max)

	di `maxhi'
	di `minlow' `maxlow' 0.9999999 1 1.0000001 `minhi' `maxhi'

	if "`c'" != "Peru" {
		spmap chat using `c'_coords, id(id) ///
		fcolor(orange orange*.7 orange*.4 orange*.1  white green*.1 green*.4 green*.7 green) ocolor(none ...) ///
		clbreaks(`minlow' `p25low' `p75low' `maxlow' 0.9999999 1 `minhi' `p25hi' `p75hi' `maxhi') clmethod(custom) ///
		legjunction("to") legorder(lohi) legend(label(2 "{bf:Decrease}") label(3 " ") label(4 " ") label(5 " ") ///
		label(6 "{bf:No change}" ) label(7 " ") label(8 " ") label(9 " ")  label(10 "{bf:Increase}") row(1) pos(6))   ///
		legtitle("{bf:Change:} ") ///
		line(data("`c'_roads_coords_wI")  ///
		color(black*.3 black*.4 black*.7 black) size(0.2 0.4 0.6 1.5 ) legenda(off)  by(percentile))
	}
	
	if "`c'" == "Peru" {
		
		spmap chat using `c'_coords, id(id) ///
		fcolor(orange orange*.7 orange*.4 orange*.1  white green*.1 green*.4 green*.7 green) ocolor(none ...) ///
		clbreaks(`minlow' `p25low' `p75low' `maxlow' 0.9999999 1 `minhi' `p25hi' `p75hi' `maxhi') clmethod(custom) ///
		legjunction("to") legorder(lohi) legend(label(2 "{bf:Decrease}") label(3 " ") label(4 " ") label(5 " ") ///
		label(6 "{bf:No change}" ) label(7 " ") label(8 " ") label(9 " ")  label(10 "{bf:Increase}") row(1) pos(6))   ///
		legtitle("{bf:Change:} ") ///
		line(data("`c'_roads_coords_wI")  ///
		color(black*.3 black*.4 black*.7 black) size(0.2 0.4 0.6 1.5 ) legenda(off)  by(percentile)) ///
		polygon(data(${countries}/uscoord) select(keep if _ID==188))
		
		
	}
	
	gr export `c'.png, replace
}


